<template>
  <div>
    <h1>HomeIndex</h1>
    <p>
      <button @click="increment">Increment</button>
      <button @click="decrement">Decrement</button>
    </p>
    <div>
      <button @click="handleClick">发送事件给ipcMain</button>
      <div style="width: 100%; height: 200px">
        {{ replyMessage }}
      </div>
    </div>
    <p>Count: {{ count }}</p>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { onUnmounted, onMounted } from 'vue'

const count = ref(0)

// 定义 increment 方法
const increment = () => {
  count.value++
}

// 定义 decrement 方法
const decrement = () => {
  count.value--
}

const replyMessage = ref<string>('123')
// 发送事件给主进程
const handleClick = () => {
  if (window.electronAPI) {
    window.electronAPI.sendMessage('message', 'Hello from Vue!')
  }
}

// 监听主进程回复的消息
const handleReply = (_event: unknown, data: string) => {
  replyMessage.value = data
}
// 组件挂载时添加监听器
onMounted(() => {
  // 监听主进程的回复
  if (window.electronAPI) {
    // 监听主进程的回复
    window.electronAPI.onMessage('message', handleReply)
  }
})

// 组件卸载时移除监听器
onUnmounted(() => {
  if (window.electronAPI) {
    // 移除监听器
    window.electronAPI.onMessage('message', handleReply)
  }
})
</script>
